package com.hyfrogx.modules.manage.service.course.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.param.PayType;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.FrogxTaskCode;
import com.hyfrogx.modules.manage.dao.course.CourseOrderDao;
import com.hyfrogx.modules.manage.entity.course.CourseManageEntity;
import com.hyfrogx.modules.manage.entity.course.CourseManageSectionEntity;
import com.hyfrogx.modules.manage.entity.course.CourseOrderEntity;
import com.hyfrogx.modules.manage.entity.course.CourseOrderCountEntity;
import com.hyfrogx.modules.manage.entity.payrecord.HyPayRecord;
import com.hyfrogx.modules.manage.entity.task.TaskUserInfoEntity;
import com.hyfrogx.modules.manage.service.HyPayRecordService;
import com.hyfrogx.modules.manage.service.course.CourseManageSectionService;
import com.hyfrogx.modules.manage.service.course.CourseManageService;
import com.hyfrogx.modules.manage.service.course.CourseOrderService;
import com.hyfrogx.modules.manage.service.task.TaskRewardService;
import com.hyfrogx.modules.manage.service.task.TaskService;
import com.hyfrogx.modules.manage.service.task.TaskUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
/**
 * @author 罗春杰-技术部
 */
@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderDao, CourseOrderEntity> implements CourseOrderService {


    @Autowired
    CourseManageService manageService;

   @Autowired
    UserService userService;

    @Autowired
    HyPayRecordService payRecortService;


    @Autowired
    CourseManageSectionService sectionService;
    @Autowired
    TaskRewardService taskRewardService;
    @Autowired
    TaskUserInfoService taskUserInfoService;
    @Autowired
    TaskService hyTaskService;

    @Override
    public CourseOrderCountEntity getCourseOrderCount() {
        CourseOrderCountEntity courseOrderCount = this.baseMapper.getCourseOrderCount();
        return courseOrderCount;
    }

    @Override
    public Page selectCourseOrderList(QueryExt queryExt) {
        Map map = new HashMap();
        map.putAll(queryExt.getCondition());
        queryExt.setRecords(this.baseMapper.selectCourseOrderList(queryExt,map));
        return queryExt;
    }

    /**
     * 课程订单
     */
    @Override
    public Integer createCourseOrder(CourseOrderEntity order){
        int keyId=0;
        //	1.通过客户端给的课程id查询课程信息
        CourseManageEntity manage = manageService.getById(order.getCid());
        //	2.判断课程的id是否存在
        if(manage==null){
            throw new ServiceException("课程不存在");
        }
        int countOrder = this.count(new QueryWrapper<CourseOrderEntity>()
                .eq("uid",order.getUid()).eq("cid",order.getCid()).eq("status",1));
        if(countOrder>0){
            throw new ServiceException("课程已被购买");
        }
        //自己购买
        keyId = this.creatOrder(order, order.getUid(), manage);
        try{
            //购买课程任务
            hyTaskService.taskSenior(order.getUid(),manage.getTruePrice(), FrogxTaskCode.TaskCode.BUY_COURSE );
            //判断有没有返利用户
            if(order.getBid()!=null){
                order.setBonusBean(manage.getRebatePrice());
                userService.addBean(order.getBid(), manage.getRebatePrice());
                // 返利者蛙豆增加订单
                this.addOrder(order.getBid(), manage);
                //分销课程任务
                Integer integer = hyTaskService.taskSenior(order.getBid(), manage.getTruePrice(), FrogxTaskCode.TaskCode.RETAIL_COURSE);
                order.setBonusScore(integer);
                this.updateById(order);
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return 1;
    }

    @Override
    public Page getpayCourseInfoByid(QueryExt queryExt) {
        Map<String,Object> map = new HashMap();
        map.putAll(queryExt.getCondition());
        List<CourseManageEntity> payManageInfoById = this.baseMapper.getPayManageInfoById(map, queryExt);
        for (CourseManageEntity hyCourseManage : payManageInfoById) {
            if (hyCourseManage.getIsserialize() == 1) {
                hyCourseManage.setFinish(0);
            } else {
                // 此字段用来比较！ 当判断所有的音/视频类的章节学习完一个就+1，循环之后用来和总的章节数比较，相同则该课程学习完成
                int count = 0;
                List<CourseManageSectionEntity> sectionByUid = sectionService.manageSectionByUid(Convert.toInt(map.get("id")),
                        hyCourseManage.getId());
                Integer sectionCounts = sectionService.count(new QueryWrapper<CourseManageSectionEntity>()
                        .eq("programid",hyCourseManage.getId()).eq("isputaway",1).ne("types",1));
                for (CourseManageSectionEntity hyCourseManageSection : sectionByUid) {
                    if (hyCourseManageSection.getWatch() != null
                            && hyCourseManageSection.getWatch().equals("100%")) {
                        count++;
                    }
                    if (count == sectionCounts) {
                        hyCourseManage.setFinish(1);
                    } else {
                        hyCourseManage.setFinish(0);
                    }
                }
            }
        }
        queryExt.setRecords(payManageInfoById);
        if (payManageInfoById != null) {
            return queryExt;
        } else {
            throw new MyException("此用户还未购买过课程");
        }
    }

    /**
     * 判断金额是否足够 扣费和生产订单
     */
    public int creatOrder(CourseOrderEntity order,Long id,CourseManageEntity manage){
        int keyId =0;
        //	3.设置订单编号
        order.setOrderno(getOutNo());
        //	4.通过客户端给的用户id查询用户id账户上的钱是否足够
        int money = userService.getMoneyByUid(id);
        //	5.判断课程id是否和用户账户上的钱是否足够
        if(money<manage.getTruePrice()){
            order.setPrice(manage.getPrice());
            order.setTprice(manage.getTruePrice());
            order.setStatus(0);
            order.setPayway(0);
            order.setStartdate(new Date());
            this.baseMapper.insert(order);
            throw new ServiceException("余额不足");
        }else{
            //6.调用UserService扣费接口
            userService.reduce(id, manage.getTruePrice());
            //获取用户金额
/*          int nowMoney = userService.getMoneyByUid(id);*/
            this.costOrder(id, manage);
            //7.生产消费明细订单
            order.setPrice(manage.getPrice());
            order.setTprice(manage.getTruePrice());
            order.setStatus(1);
            order.setPayway(0);
            order.setStartdate(new Date());
            keyId=this.baseMapper.insertSelective(order);
        }
        return keyId;

    }

    /**
     * 生成订单编号
     * @return
     */
    public String getOutNo() {
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;
        String monthN;
        if(month < 10){
            monthN = "0" + month + "";
        }else{
            monthN = month + "";
        }
        int day = now.get(Calendar.DAY_OF_MONTH);
        String outNo = year + "" + monthN  + day  + "" +  System.currentTimeMillis() + "";
        return outNo;
    }

    public int costOrder(Long uid, CourseManageEntity manage) {
        // 生成蛙豆订单
        User user = userService.getById(uid);
        HyPayRecord payRecord = new HyPayRecord();
        payRecord.setCreatedate(new Date());
        payRecord.setTotal(manage.getTruePrice());
        payRecord.setMoney(0);
        payRecord.setNum(0);
        payRecord.setType(PayType.buy_course.getCode());
        payRecord.setPercentCoin(0);
        payRecord.setPercent(0.0F);
        payRecord.setYid(FrogConstant.admin_uid);
        // 扣费者id
        payRecord.setUid(uid);
        // 资源对应id(本次为抽取无资源)
        payRecortService.save(payRecord);
        return 1;
    }

    public int addOrder(Long uid, CourseManageEntity manage) {
        // 生成返利者蛙豆订单
        User user = userService.getById(uid);
        HyPayRecord payRecord = new HyPayRecord();
        payRecord.setCreatedate(new Date());
        payRecord.setTotal(manage.getRebatePrice());
        payRecord.setMoney(0);
        payRecord.setNum(0);
        payRecord.setType(PayType.share_course_bonus.getCode());
        payRecord.setPercentCoin(0);
        payRecord.setPercent(0f);
        payRecord.setYid(uid);
        // 扣费者id
        payRecord.setUid(FrogConstant.admin_uid);
        // 资源对应id(本次为抽取无资源)
        payRecortService.save(payRecord);
        return 1;
    }

}
